package com.bbg.amyam.web.util;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import com.bbg.amyam.domain.model.School;
import com.bbg.amyam.web.mvc.cachemanager.SchoolCacheManager;
import com.bbg.amyam.web.mvc.exception.NoSchoolFoundException;

public class RequestPathPaser {
	private static final ArrayList<String> RESERVED_PATH;
	private static final ArrayList<String> DOMAIN_CLASSES ;
	static{
		RESERVED_PATH=new ArrayList<String>();
		RESERVED_PATH.add("jqwidgets");
		RESERVED_PATH.add("resources");
		
		DOMAIN_CLASSES=new ArrayList<String>();
		//DONT REMOVE START
DOMAIN_CLASSES.add("courses");
DOMAIN_CLASSES.add("documents");
DOMAIN_CLASSES.add("employees");
DOMAIN_CLASSES.add("newsarticles");
DOMAIN_CLASSES.add("parents");
DOMAIN_CLASSES.add("passwordretrievekeys");
DOMAIN_CLASSES.add("persons");
DOMAIN_CLASSES.add("profiles");
DOMAIN_CLASSES.add("profilepictures");
DOMAIN_CLASSES.add("programs");
DOMAIN_CLASSES.add("programcategorys");
DOMAIN_CLASSES.add("registrations");
DOMAIN_CLASSES.add("schools");
DOMAIN_CLASSES.add("schoolacdemicperiods");
DOMAIN_CLASSES.add("schoolroles");
DOMAIN_CLASSES.add("schooltags");
DOMAIN_CLASSES.add("students");

		//DONT REMOVE END
		
	}
	
	public static RequestPathParameter parse(HttpServletRequest request) throws NoSchoolFoundException{
		String requestPath = request.getRequestURI().substring(
				request.getContextPath().length() + 1);
		
		StringBuffer requestURLBuffer = request.getRequestURL();
		
		while (requestPath.startsWith("/")) {
			requestPath = requestPath.substring(1);
		}
		
		requestPath=StringUtils.substringBefore(requestPath, "?");
		String[] pathParameters = StringUtils.split(requestPath, '/');
		RequestPathParameter pathParameter=new RequestPathParameter();
		if(pathParameters.length>0){
			if(!RESERVED_PATH.contains(pathParameters[0])){
				School school;
				String viewName=null;
				String actionName="";
				String requestURL=null;
				if(checkDomainnames(pathParameters[0])){
					 school = SchoolCacheManager.getSchool("default");
					 viewName="support_view";
				}else{
					school = SchoolCacheManager.getSchool(pathParameters[0]);
					
					if(pathParameters.length>1){
						viewName=pathParameters[1];
					}
					if(pathParameters.length>2){
						actionName=pathParameters[2];
					}
					requestURL=StringUtils.substringBefore(requestURLBuffer.toString(), pathParameters[0]);
				}
				pathParameter.setSchool(school);
				pathParameter.setViewName(viewName);
				pathParameter.setActionName(actionName);
				pathParameter.setRequestURL(requestURL);
				return pathParameter;
			}
		}
		return null;
	}

	private static boolean checkDomainnames(String parameter) {

		for(String name:DOMAIN_CLASSES){
			if(name.equals(parameter)){
				return true;
			}
		}
		return false;
	}

	
	
	
}
